package top.lshaci.learning.jvm.gc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * STWDemo
 *
 * @author lshaci
 * @date 2020/8/6 16:34
 * @since 1.0.0
 */
public class STWDemo {

    public static class WorkThread extends Thread {

        List<byte[]> list = new ArrayList<>();

        @Override
        public void run() {
            try {
                while (true) {
                    for (int i = 0; i < 1000; i++) {
                        byte[] buffer = new byte[1024];
                        list.add(buffer);
                    }

                    if (list.size() > 10000) {
                        list.clear();
                        System.gc();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static class PrintThread extends Thread {
        final long start = System.currentTimeMillis();

        @Override
        public void run() {
            try {
                while (true) {
                    long t = System.currentTimeMillis() - start;
                    System.err.println(t / 1000 + "." + t % 1000);
                    TimeUnit.SECONDS.sleep(1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            super.run();
        }
    }

    public static void main(String[] args) {
        Thread work = new WorkThread();
        Thread print = new PrintThread();
        work.start();
        print.start();
    }
}
